//% color="#ff9a00" iconWidth=50 iconHeight=40
namespace fan_DC{
  
    //% block="打开 引脚[PIN] 的风扇" blockType="command"
    //% PIN.shadow="normal" PIN.defl=" " 

    export function fan_DCopen(parameter: any, block: any) {      
     let pin=parameter.PIN.code;  
     let obj=parameter.PIN.parType
     console.log(parameter)
     //根据输入积木生成对象名
     if(obj=="unihiker.unihikerPin"){//行空板引脚
         obj=extractPinCode(pin)
         Generator.addInitHeader(`fan_DCopen${obj}`,`p_${obj}_in=Pin(Pin.P${obj}, Pin.PWM)`);
     }
   
     Generator.addImport("from pinpong.board import Board,Pin");
      
     Generator.addCode(`p_${obj}_in.write_analog(500)`);
   
    }

    //% block="关闭 引脚[PIN] 的风扇" blockType="command"
    //% PIN.shadow="normal" PIN.defl=" " 
    export function fan_DCclose(parameter: any, block: any) {      
      let pin=parameter.PIN.code;  
      let obj=parameter.PIN.parType
      console.log(parameter)
      //根据输入积木生成对象名
      if(obj=="unihiker.unihikerPin"){//行空板引脚
          obj=extractPinCode(pin)
          Generator.addInitHeader(`fan_DCopen${obj}`,`p_${obj}_in=Pin(Pin.P${obj}, Pin.PWM)`)
      }
    
      Generator.addImport("from pinpong.board import Board,Pin");
       
      Generator.addCode(`p_${obj}_in.write_analog(0)`);
    
     }

     //% block="引脚[PIN] 风扇转速[SR]" blockType="command"
    //% PIN.shadow="normal" PIN.defl=""
    //% SR.shadow="range"   SR.params.min=0    SR.params.max=100    SR.defl=0
    export function fan_DCspeed(parameter: any, block: any) {      
      let pin=parameter.PIN.code;  
      let obj=parameter.PIN.parType;
      let sp=parameter.SR.code;
   
      //根据输入积木生成对象名
      Generator.addImport("from pinpong.board import Board,Pin");
      if(obj=="unihiker.unihikerPin"){//行空板引脚
          obj=extractPinCode(pin)
          Generator.addInitHeader(`fan_DCopen${obj}`,`p_${obj}_in=Pin(Pin.P${obj}, Pin.PWM)`)

   }
   console.log(`${sp}`)
   if(`${sp}` === "0"){
      Generator.addCode(`p_${obj}_in.write_analog(0)`);

   }else{
      Generator.addCode(`p_${obj}_in.write_analog(round(${sp}*((1023-250)/100)+200))`);
   }
   
}


    function extractPinCode(input: string): string | null {
      // 正则表达式匹配 "Pin.Px" 风格的字符串
      const match = input.match(/Pin\.P(\d+)/);
      // 如果匹配成功，返回匹配的部分（不包括"Pin."）
      return match ? match[1] : null;
    }
    
    
}